package com.roger.springcloudGreenwich.controller;

import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.agent.model.Check;
import com.orbitz.consul.model.agent.Member;
import com.roger.springcloudGreenwich.service.ConsulService;
import com.roger.springcloudGreenwich.service.FeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by admin on 2020/4/2.
 */
@RestController
@Slf4j
@RequestMapping("/consulClient")
public class ConsulController {

    @Autowired
    private ConsulService consulService;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/deleteServiceId/{serviceId}")
    public String deleteServiceId(@PathVariable String serviceId){
        try {
            consulService.deleteConsulServiceId(serviceId);
            return "success";
        }catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
    }

    @GetMapping("/getMember")
    public Object getMember(){
        try {
            List<Member> list = consulService.getConsulMember();
            return list;
        }catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
    }


    //引入LoadBalancerClient
    @Autowired
    private LoadBalancerClient loadBalancer;
    @GetMapping("/test")
    public String test(){
        //定义服务提供者的服务名
        String serviceName = "consul-provider";
        //通过loadBalancer找到服务实例
        ServiceInstance serviceInstance = loadBalancer.choose(serviceName);
        //通过实例找到URI
        String uri = serviceInstance.getUri().toString();
        //拼接出URL
        String url = uri + "/provider/test";
        //发送请求
        String result = restTemplate.getForObject(url, String.class);
        return result;
    }

    @Autowired
    FeignService feignService;

    @GetMapping("/feignTest")
    public String feignTest(){
        String result = feignService.testClient();
        return result;
    }

}
